package cn.yangliu.web;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.yangliu.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 杨柳
 * @date 2019-05-31 21:11
 */
@RequestMapping("/user")
@RestController
@Slf4j
@Api
public class UserController {
    private Map<Long, User> userMap = new LinkedHashMap<>();

    {
        for (long i = 0; i < 10L; i++) {
            User user = new User();
            user.setId(i + 1);
            user.setUsername("user" + (i + 1));
            user.setPassword("123456");
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setRemark("new user");
            userMap.put(user.getId(), user);
        }
    }

    /**
     * 新增或修改
     */
    @PostMapping
    @ApiOperation("保存")
    public User save(@RequestBody User data) {
        data.setId(System.currentTimeMillis());
        userMap.put(data.getId(), data);
        return data;
    }

    /**
     * 列表查询
     */
    @GetMapping
    @PreAuthorize("hasPermission(authentication.principal,'user:find')")
    public List<User> findAll() {
        return new ArrayList<>(userMap.values());
    }

    /**
     * 查询单个
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasPermission(authentication.principal,'user:query')")
    public User findById(@PathVariable("id") Long id) {
        return userMap.get(id);
    }

    /**
     * 删除
     */
    @DeleteMapping
    @PreAuthorize("hasRole('admin')")
    public boolean deleteById(@RequestBody Long id) {
        boolean flag = userMap.containsKey(id);
        if (flag) {
            userMap.remove(id);
        }
        return flag;
    }


}
